/**
 * 检测模块
 * @author holyhigh
 */
const ua: string = (window as any).userAgent || navigator.userAgent

/**
 * 是否iPhone平台
 * @return {boolean}
 */
function isIPhone(): boolean {
  return /\biphone\b/i.test(ua)
}

/**
 * 是否iPad平台
 * @return {boolean}
 */
function isIPad(): boolean {
  return (
    /\bipad\b/i.test(ua) ||
    (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) //ios>13
  )
}

/**
 * 是否android平台
 * @return {boolean}
 */
function isAndroid(): boolean {
  return /\bandroid\b/i.test(ua) && /\blinux\b/i.test(ua)
}

/**
 * 获取屏幕分辨率
 * @return {object} {w,h}
 */
function getScreenResolution(): { w: number; h: number } {
  return {
    w: screen.width * window.devicePixelRatio,
    h: screen.height * window.devicePixelRatio,
  }
}

/**
 * 获取有效屏幕分辨率。剔除工具栏
 * @return {object} {w,h}
 */
function getAvailScreenResolution(): { w: number; h: number } {
  return {
    w: screen.availWidth * window.devicePixelRatio,
    h: screen.availHeight * window.devicePixelRatio,
  }
}

/**
 * 检测当前环境是否在iframe中
 * @return {boolean}
 */
function isInIframe(): boolean {
  return self != top
}

/**
 * 检测当前页面是否已开启全屏，包括F11或元素发起
 * @return {boolean}
 */
function isFullscreen(): boolean {
  return (
    document.fullscreenElement !== null ||
    document.documentElement.clientHeight === screen.height
  )
}

/**
 * 获取页面根字体大小
 * @return {number} 像素大小
 */
function getRootFontSize(): number {
  const fontSize = window
    .getComputedStyle(document.body, null)
    .getPropertyValue('font-size')
  return parseInt(fontSize)
}

//https://developer.mozilla.org/en-US/docs/Web/CSS/resolution
const DP_RATIO = 96

/**
 * 获取当前页面dppx
 * @return {number}
 */
function getDppx(): number {
  return window.devicePixelRatio || 0
}

/**
 * 获取当前页面的dpi
 * @return {number}
 */
function getDpi(): number {
  return getDppx() * DP_RATIO
}

/**
 * 检测当前页面可视区是否横屏
 * @return {boolean}
 */
function isLandscape(): boolean {
  return matchMedia('(orientation:landscape)').matches
}

/**
 * 检测当前页面可视区是否竖屏
 * @return {boolean}
 */
function isPortrait(): boolean {
  return matchMedia('(orientation:portrait)').matches
}

export {
  isIPhone,
  isIPad,
  isAndroid,
  isInIframe,
  isFullscreen,
  getScreenResolution,
  getAvailScreenResolution,
  getDppx,
  getDpi,
  isLandscape,
  isPortrait,
}
